#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

import os
import sys
from PySide import QtGui, QtCore
from .data.parse_yaml import parse_yaml_file
from .asset_library_dialog import LibraryWidget


class SetConfig(object):
    def __init__(self, parent=None, config_file=None):
        self._config_file = config_file
        self._parent = parent #QtGui.QApplication.activeWindow()

    def get_data(self):
        config_file_path = os.path.join(self.get_folder_path('config'), self._config_file)
        print config_file_path
        if not os.path.isfile(config_file_path):
            return
        return parse_yaml_file(config_file_path)

    def get_folder_path(self, name):
        return os.path.join(os.path.dirname(os.path.dirname(__file__)), name)

    def get_library_data(self):
        data = self.get_data()
        action_mapping = data.get('action_mapping')
        action_manager = {}
        for step in action_mapping:
            step_actions = action_mapping.get(step)
            if not step_actions:
                continue
            step_action_manager = {}
            for action_name in step_actions:
                action_file = step_actions.get(action_name)
                action_instance = self._get_instance(action_file)
                if not action_instance:
                    continue
                step_action_manager[action_name] = action_instance
            if step_action_manager:
                action_manager[step] = step_action_manager

        return [data.get('root_paths'), action_manager]

    def _get_instance(self, hook_file):
        hooks_path = self.get_folder_path('hooks')
        if hooks_path not in sys.path:
            sys.path.append(hooks_path)
        name = hook_file.split('.py')[0]
        module = __import__(name)
        del sys.modules[name]
        module = __import__(name)
        if hasattr(module, 'execute'):
            return module.execute
        return

    def get_win(self):
        library_data = self.get_library_data()
        return LibraryWidget(parent=self._parent, library_data=library_data)
        # lw = LibraryWidget(library_data=library_data)
        # lw.show()

